﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using SingleBlog.Web.Areas.Admin.Models;
using System;
using System.Threading.Tasks;

namespace SingleBlog.Web.Areas.Admin.Controllers
{
    using Core.Data;
    [Area("admin")]
    [Authorize(Roles = SingleBlogRole.ADMINISTRATOR)]
    public class HomeController:Controller
    {
        private SignInManager<SingleBlogUser> _signInManager;
        public HomeController(SignInManager<SingleBlogUser> signInManager)
        {
            _signInManager = signInManager;
        }

        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (returnUrl.IsNullOrEmpty())
                {
                    return RedirectToAction("Index");
                }
                return Redirect(returnUrl);
            }

            return View(new LoginViewModel { ReturnUrl = returnUrl });
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login([FromForm]LoginViewModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Account, model.Password, true, false);

            if (result.Succeeded)
            {
                if (model.ReturnUrl.IsNullOrEmpty())
                {
                    return RedirectToAction("Index");
                }
                return Redirect(model.ReturnUrl);
            }

            ModelState.AddModelError("", "帐号或密码错误");
            return View(model);
        }

        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Login");
        }
        
        public IActionResult Index() => View();
    }
}
